<template>
  <div style="width: 50%;border: 1px solid;">
    <div class="card" style="padding: 25px 30px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);">
      <div style="font-size: 20px;color: red;display: flex;align-items: center;justify-content: center">
        <span style="margin-bottom: 20px">个人创新创业学分认证申请</span>
      </div>
      <el-form :model="data.form" ref="formRef" :rules="data.rules" label-width="180px" style="padding-right: 50px">
        <el-form-item prop="typeId" label="申请创新创业类型">
          <el-select v-model="data.form.typeId" @change="handleTypeChange" placeholder="请选择创新创业类型">
            <el-option v-for="item in data.typeList" :key="item.typeId" :value="item.typeId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="actId" label="申请创新创业活动项">
          <el-select v-model="data.form.actId" placeholder="请先选择创新创业类型" :disabled="!data.form.typeId">
            <el-option v-for="item in filteredActList" :key="item.actId" :value="item.actId" :label="item.actName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="creditCount" label="申请学分">
          <el-input v-model="data.form.creditCount" placeholder="请先选择创新创业活动项" type="number" disabled></el-input>
        </el-form-item>
        <el-form-item prop="appData" label="上传申请材料">
          <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              :action="data.uploadAction"
              :multiple="true"
              :limit="3"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
          >
            <el-button type="primary">点击上传材料</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持PDF、Word和图片文件，大小不超过5MB，最多上传3个文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <div style="text-align: center;margin-top: 20px">
          <el-button style="padding: 10px 25px" type="primary" @click="handleSubmitApply">提交个人申请</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {computed, reactive, ref, watch} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import alovaInstance from "@/utils/request.js";

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  rules: {
    typeId: [{ required: true, message: '请选择创新创业类型', trigger: 'blur' }],
    actId: [{ required: true, message: '请选择创新创业活动项', trigger: 'blur' }],
    creditCount: [{ required: true, message: '申请学分为空', trigger: 'blur' }],
    appData: [{ required: true, message: '请上传申请材料', trigger: 'blur' }]
  },
  form: {
    appData: [] // 存储上传文件的URL
  },
  typeList: [],
  actCreditList: [],
  uploadAction: 'http://localhost:9090/files/upload' // 文件上传接口地址
});

const formRef = ref();
const fileList = ref([]); // 存储已上传的文件列表

// 加载类型列表
const loadTypeList = () => {
  alovaInstance.Get('/collegeAdminActiveType/selectActiveTypeList').then(res => {
    if (res.code === '200') {
      data.typeList = res.data;
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message || '网络错误，请稍后重试');
  });
};

// 加载活动列表
const loadActCreditList = () => {
  alovaInstance.Get('/collegeAdminActiveCredit/selectActiveCreditList').then(res => {
    if (res.code === '200') {
      data.actCreditList = res.data;
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message || '网络错误，请稍后重试');
  });
};

// 处理提交申请（包含二次确认）
const handleSubmitApply = () => {
  // 先进行表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      // 显示二次确认弹窗
      ElMessageBox.confirm(
          '确认提交当前申请吗？提交后将无法修改，进入等待审核',
          '提示',
          {
            confirmButtonText: '确 认',
            cancelButtonText: '取 消',
            type: 'warning'
          }
      ).then(() => {
            // 用户点击确认后的处理
            submitApply();
      }).catch(() => {
        // 用户点击取消后的处理（无需操作，直接返回）
        ElMessage.warning('已取消提交申请');
      });
    }
  });
};

// 真正提交申请的逻辑
const submitApply = () => {
  // 将文件列表url数组转换为字符串
  data.form.appData = data.form.appData.join(',');
  data.form.stuId = data.user.stuId;
  alovaInstance.Post('/applicationRecord/submitApply', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('提交申请成功');
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message || '网络错误，请稍后重试');
  });
  setTimeout(() => { location.reload(); }, 500);
};

// 计算属性：根据类型ID过滤活动列表
const filteredActList = computed(() => {
  if (!data.form.typeId) return []; // 未选择类型时返回空活动数组
  return data.actCreditList.filter(item => item.typeId === data.form.typeId);
})

// 类型选择变化时的处理
const handleTypeChange = () => {
  // 选择类型后清空活动选择
  data.form.actId = null;
}

//监听活动类型的选择
watch(() => data.form.actId, (newActId) => {
  if (!newActId) return;
  const selectedAct = data.actCreditList.find(item => item.actId === newActId);
  if (selectedAct) {
    data.form.creditCount = selectedAct.creditCount;
  }
})

// 上传前校验文件
const beforeUpload = (file) => {
  // 检查文件类型
  const isPDF = file.type === 'application/pdf';
  const isWord = file.type.includes('word') || file.type.includes('excel');
  const isImage = file.type.includes('image');

  if (!(isPDF || isWord || isImage)) {
    ElMessage.error('仅支持PDF、Word和图片文件上传');
    return false;
  }

  // 检查文件大小 (5MB = 5 * 1024 * 1024)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过5MB');
    return false;
  }

  return true;
};

// 文件超出限制处理
const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传3个文件，当前已选择${data.form.appData.length}个文件`);
};

// 文件移除处理
const handleRemove = (file) => {
  ElMessage.info(`已移除文件: ${file.name}`);
  // 从表单数据中移除对应的文件URL
  data.form.appData = data.form.appData.filter(url => url !== file.response);
};

// 上传成功处理
const handleSuccess = (response, file) => {
  ElMessage.success(`文件 ${file.name} 上传成功`);
  // 将上传成功的文件URL添加到表单数据中
  console.log(response)
  data.form.appData.push(response.data);
};

// 上传失败处理
const handleError = (error, file) => {
  ElMessage.error(`文件 ${file.name} 上传失败，请重试`);
  console.error('文件上传失败:', error);
};

loadTypeList();
loadActCreditList();
</script>